#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORT 8080
#define buf_size 128

//字符串反序列化
int deserialize_string(const uint8_t* buf, char* str, size_t str_size)
{
    uint32_t net_len;
    memcpy(&net_len,buf,sizeof(net_len));
    size_t len = ntohl(net_len);

    if(len >= str_size)
    {
        return -1;
    }

    memcpy(str,buf + sizeof(net_len),len);
    str[len] = '\0';

    return sizeof(net_len) + len;
}

//验证用户名和密码
int authen(const char* username, const char* password)
{
    return (strcmp(username,"admin") == 0 && strcmp(password,"password") == 0);
}

int main(int argc, char const *argv[])
{
    
    int sockfd,new_socket;
    struct sockaddr_in addr;
    int opt = 1;
    int addrlen = sizeof(addr);

    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == 0)
    {
        printf("创建失败\n");
        return -1;
    }

    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt,sizeof(opt)))
    {
        printf("setsockopt");
        exit(EXIT_FAILURE);
    }

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(PORT);

    if(bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0)
    {
        printf("绑定失败\n");
        return -1;
    }

    if(listen(sockfd,3) < 0)
    {
        printf("监听失败\n");
        return -1;
    }

    printf("等待连接 ,正在监听端口 : %d\n",PORT);

    while (1)
    {
        if (new_socket = accept(sockfd, (struct sockaddr*)&addr, (socklen_t*)&addrlen))
        {
            printf("连接失败\n");
            return -1;
        }

        uint8_t buf[buf_size];

        int bytes_read = read(new_socket,buf,buf_size);

        if(bytes_read > 0)
        {
            int offset = 0;
            char username[256];
            char password[256];

            int username_len = deserialize_string(buf + offset, username, sizeof(username));

            if(username_len < 0)
            {
                printf("用户名反序列化失败\n");
                close(new_socket);
                continue;
            }
            
            offset+= username_len;

            int password_len = deserialize_string(buf + offset, password, sizeof(password));

            if (password_len < 0)
            {
                printf("密码反序列化失败\n");
                close(new_socket);
                continue;
                /* code */
            }
            printf("收到登录请求： 用户名=%s, 密码=%s\n", username,password);

            uint8_t response = authen(username,password) ? 1 : 0;

            send(new_socket,&response,1,0);

            if (response)
            {
                printf("登录成功\n");
                /* code */
            }
            else
            {
                printf("登录失败\n");
            }
            
        }

        close(new_socket);
    }
    
    return 0;
}
